package cc.ufinity.networkdiagnose.manager;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public final class DBManager {

	private static final String CREATE_FTP = "create table ftp (_id integer primary key autoincrement, address text not null, "
			+ "port integer not null, username text not null, password text not null);";
	private static final String CREATE_TASK = "create table task (_id integer primary key autoincrement, "
			+ "address text not null,apname text not null,taskid text not null);";
	private static final String CREATE_ACCOUNT = "create table account (_id integer primary key autoincrement, "
			+ "username text not null, password text, autologin integer);";
	private static final String DATABASE_NAME = "NetworkTest.db";
	private static final int DATABASE_VERSION = 1;

	private static DBManager dbManager = null;
	private SQLiteDatabase mDb;

	class DbHelper extends SQLiteOpenHelper {

		public DbHelper(Activity context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL(CREATE_FTP);
			db.execSQL(CREATE_TASK);
			db.execSQL(CREATE_ACCOUNT);
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			db.execSQL("DROP TABLE IF EXISTS ftp");
			db.execSQL("DROP TABLE IF EXISTS task");
			db.execSQL("DROP TABLE IF EXISTS account");
			onCreate(db);
		}
	}

	public DBManager(Activity ctx) {
		DbHelper help = new DbHelper(ctx);
		mDb = help.getWritableDatabase();
	}

	@Deprecated
	public static DBManager getInstance(Activity ctx) {
		if (null == dbManager) {
			dbManager = new DBManager(ctx);
		}

		return dbManager;
	}

	public void release() {
		mDb.close();
	}

	public FTPConfig getFtp() {
		FTPConfig ftp = null;
		Cursor mCursor = mDb.query("ftp", null, null, null, null, null, null);
		if (mCursor.moveToFirst()) {
			ftp = new FTPConfig();
			ftp.id = mCursor.getInt(0);
			ftp.address = mCursor.getString(1);
			ftp.port = mCursor.getInt(2);
			ftp.userName = mCursor.getString(3);
			ftp.password = mCursor.getString(4);
		}
		return ftp;
	}

	public int deleteFtp() {
		return mDb.delete("ftp", null, null);
	}

	public boolean saveFtp(FTPConfig ftp) {
		ContentValues values = new ContentValues();
		values.put("address", ftp.address);
		values.put("port", ftp.port);
		values.put("username", ftp.userName);
		values.put("password", ftp.password);
		FTPConfig temp = getFtp();
		if (null == temp) {
			return (mDb.insert("ftp", null, values)) > 0;
		} else {
			return (mDb.update("ftp", values, "_id=?", new String[] { ""
					+ temp.id })) > 0;
		}
	}

	public List<TaskConfig> getTask(String apname, String taskid) {
		List<TaskConfig> tasks = new ArrayList<TaskConfig>();
		TaskConfig task = null;
		String where = "apname=? and taskid=?";
		String whereArg[] = new String[] { apname, taskid };
		Cursor mCursor = mDb.query("task", null, where, whereArg, null, null,
				null);
		while (mCursor.moveToNext()) {
			task = new TaskConfig();
			task.id = mCursor.getInt(0);
			task.address = mCursor.getString(1);
			tasks.add(task);
		}
		return tasks;
	}

	public List<TaskConfig> getTask() {
		List<TaskConfig> tasks = new ArrayList<TaskConfig>();
		TaskConfig task = null;
		Cursor mCursor = mDb.query("task", null, null, null, null, null, null);
		while (mCursor.moveToNext()) {
			task = new TaskConfig();
			task.id = mCursor.getInt(0);
			task.address = mCursor.getString(1);
			task.apname = mCursor.getString(2);
			task.taskid = mCursor.getString(3);
			tasks.add(task);
		}
		return tasks;
	}

	public boolean taskFinished(List<TaskConfig> tasks, String address,
			String taskid) {
		Iterator<TaskConfig> it = tasks.iterator();
		TaskConfig task = null;
		boolean exist = false;
		while (it.hasNext()) {
			task = it.next();
			String addr = task.address;
			String id = String.valueOf(task.taskid);
			if (addr.equalsIgnoreCase(address) && id.equalsIgnoreCase(taskid)) {
				exist = true;
				break;
			}
		}
		return exist;
	}

	public void saveTask(String address, String apname, String taskid) {
		List<TaskConfig> tasks = getTask();
		Iterator<TaskConfig> it = tasks.iterator();
		TaskConfig task = null;
		boolean exist = false;
		while (it.hasNext()) {
			task = it.next();
			if (task.address.equalsIgnoreCase(address)
					&& String.valueOf(task.id).equalsIgnoreCase(taskid)) {
				exist = true;
				break;
			}
		}
		if (!exist) {
			ContentValues values = new ContentValues();
			values.put("address", address);
			values.put("apname", apname);
			values.put("taskid", taskid);
			mDb.insert("task", null, values);
			// mDb.update("task", values, "_id=?", new String[] { "" + temp.id
			// });
		}
	}

	public Account getAccount() {
		Account account = null;
		Cursor mCursor = mDb.query("account", null, null, null, null, null,
				null);
		if (mCursor.moveToFirst()) {
			account = new Account();
			account.id = mCursor.getInt(0);
			account.userName = mCursor.getString(1);
			account.password = mCursor.getString(2);
			Log.e("account", "" + account.password);
			account.autoLogin = mCursor.getInt(3);
		}
		return account;
	}

	public boolean saveAccount(Account account) {
		ContentValues values = new ContentValues();
		values.put("username", account.userName);
		values.put("password", account.password);
		values.put("autologin", account.autoLogin);

		Account temp = getAccount();
		if (null == temp) {
			return (mDb.insert("account", null, values)) > 0;
		} else {
			return (mDb.update("account", values, "_id=?", new String[] { ""
					+ temp.id })) > 0;
		}
	}
}
